package com.stars.system.fitness.service.impl;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.stars.system.fitness.domain.FitnessBasic;
import com.stars.system.fitness.domain.FitnessRecord;
import com.stars.system.fitness.mapper.FitnessBasicMapper;
import com.stars.system.fitness.service.IFitnessBasicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 我的习惯Service业务层处理
 * 
 * @author shuaibizhe
 * @date 2022-09-09
 */
@Service
public class FitnessBasicServiceImpl implements IFitnessBasicService
{
    @Autowired
    private FitnessBasicMapper fitnessBasicMapper;

    @Autowired
    private RedisCache redisCache;

    public static final String PLACE = "place_map";

    public static final String TYPE = "type_map";

    public static final String UNIT = "unit_map";

    public static final String TYPE_UNIT = "type_unit_map";

    /**
     * 查询我的习惯
     * 
     * @param basicId 我的习惯主键
     * @return 我的习惯
     */
    @Override
    public FitnessBasic selectFitnessBasicByBasicId(String basicId)
    {
        return fitnessBasicMapper.selectFitnessBasicByBasicId(basicId);
    }

    /**
     * 查询我的习惯列表
     * 
     * @param fitnessBasic 我的习惯
     * @return 我的习惯
     */
    @Override
    public List<FitnessBasic> selectFitnessBasicList(FitnessBasic fitnessBasic)
    {
        fitnessBasic.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        return fitnessBasicMapper.selectFitnessBasicList(fitnessBasic);
    }

    /**
     * 新增我的习惯
     * 
     * @param fitnessBasic 我的习惯
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertFitnessBasic(FitnessBasic fitnessBasic)
    {
        fitnessBasic.setCreateTime(DateUtils.getNowDate());
        fitnessBasic.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        fitnessBasic.setBasicId(UUID.randomUUID().toString());
        Map<String, Map> dict = redisCache.getCacheMap("basicDict");
        // 同部位同类型的健身是相同健身
        if (dict.get(TYPE).containsKey(fitnessBasic.getBasicType())) {
            throw new ServiceException("已存在该健身类型的习惯");
        }
        if (StringUtils.isNotEmpty(fitnessBasic.getBasicParent()) && StringUtils.isEmpty(fitnessBasic.getBasicParentDesc())) {
            fitnessBasic.setBasicParentDesc((String) dict.get(PLACE).get(fitnessBasic.getBasicParent()));
        }
        if (StringUtils.isNotEmpty(fitnessBasic.getBasicType()) && StringUtils.isEmpty(fitnessBasic.getBasicTypeDesc())) {
            fitnessBasic.setBasicTypeDesc((String) dict.get(TYPE).get(fitnessBasic.getBasicType()));
        }
        if (StringUtils.isNotEmpty(fitnessBasic.getBasicUnit()) && StringUtils.isEmpty(fitnessBasic.getBasicUnitDesc())) {
            fitnessBasic.setBasicUnitDesc((String) dict.get(UNIT).get(fitnessBasic.getBasicUnit()));
        }
        int rows = fitnessBasicMapper.insertFitnessBasic(fitnessBasic);
        insertFitness(fitnessBasic);
        return rows;
    }

    /**
     * 修改我的习惯
     * 
     * @param fitnessBasic 我的习惯
     * @return 结果
     */
    @Transactional
    @Override
    public int updateFitnessBasic(FitnessBasic fitnessBasic)
    {
        fitnessBasicMapper.deleteFitnessByBasicId(fitnessBasic.getBasicId());
        insertFitness(fitnessBasic);
        return fitnessBasicMapper.updateFitnessBasic(fitnessBasic);
    }

    /**
     * 批量删除我的习惯
     * 
     * @param basicIds 需要删除的我的习惯主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteFitnessBasicByBasicIds(String[] basicIds)
    {
        fitnessBasicMapper.deleteFitnessByBasicIds(basicIds);
        return fitnessBasicMapper.deleteFitnessBasicByBasicIds(basicIds);
    }

    /**
     * 删除我的习惯信息
     * 
     * @param basicId 我的习惯主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteFitnessBasicByBasicId(String basicId)
    {
        fitnessBasicMapper.deleteFitnessByBasicId(basicId);
        return fitnessBasicMapper.deleteFitnessBasicByBasicId(basicId);
    }

    /**
     * 新增fitness信息
     * 
     * @param fitnessBasic 我的习惯对象
     */
    public void insertFitness(FitnessBasic fitnessBasic)
    {
        List<FitnessRecord> fitnessList = fitnessBasic.getFitnessList();
        String basicId = fitnessBasic.getBasicId();
        if (StringUtils.isNotNull(fitnessList))
        {
            List<FitnessRecord> list = new ArrayList<>();
            for (FitnessRecord fitness : fitnessList)
            {
                fitness.setBasicId(basicId);
                list.add(fitness);
            }
            if (list.size() > 0)
            {
                fitnessBasicMapper.batchFitness(list);
            }
        }
    }

    /**
     * 查询我的习惯字典值
     *
     * @return res 各字典的集合
     */
    @Override
    @Log
    public Map<String, Object> selectFitnessBasicDict() {
        //字典值，back：背
        Map place_map = new HashMap();
        Map type_map = new HashMap();
        Map unit_map = new HashMap();
        Map type_unit_map = new HashMap();
        List<FitnessBasic> list = fitnessBasicMapper.selectFitnessBasicList(new FitnessBasic(){
            {
                setCreateBy(SecurityUtils.getLoginUser().getUsername());
            }
        });
        for (FitnessBasic fitnessBasic : list) {
            place_map.put(fitnessBasic.getBasicParent(),fitnessBasic.getBasicParentDesc());
            type_map.put(fitnessBasic.getBasicType(),fitnessBasic.getBasicTypeDesc());
            unit_map.put(fitnessBasic.getBasicUnit(),fitnessBasic.getBasicUnitDesc());
            type_unit_map.put(fitnessBasic.getBasicType(),fitnessBasic.getBasicUnitDesc());
        }
        Map<String,Object> res = new HashMap<String, Object>() {
            {
                put(PLACE, place_map);
                put(TYPE, type_map);
                put(UNIT, unit_map);
                put(TYPE_UNIT, type_unit_map);
            }
        };
        redisCache.setCacheMap("basicDict",res);
        return res;
    }

    /**
     * 查询我的习惯树形结构数据
     *
     * @return tree 树形结构，父集是部位，子集是健身类型
     */
    @Override
    public List selectFitnessBasicTree() {
        List tree = new ArrayList();
        List<FitnessBasic> list = fitnessBasicMapper.selectFitnessBasicList(new FitnessBasic(){
            {
                setCreateBy(SecurityUtils.getLoginUser().getUsername());
            }
        });
        Map<String,Boolean> parents = new HashMap();
        Map rel = new HashMap();
        for (FitnessBasic fitnessBasic : list) {
            // 放父级
            if (!parents.containsKey(fitnessBasic.getBasicParent()) || !parents.get(fitnessBasic.getBasicParent())) {
                if (!CollectionUtils.isEmpty(parents)) {
                    // 避免引用传递
                    tree.add(new HashMap<>(rel));
                }
                rel.put("value",fitnessBasic.getBasicParent());
                rel.put("label",fitnessBasic.getBasicParentDesc());
                rel.put("disabled",false);
                rel.put("children",new ArrayList<HashMap>(){
                    {
                        add(new HashMap(){
                            {
                                put("value",fitnessBasic.getBasicType());
                                put("label",fitnessBasic.getBasicTypeDesc());
                                put("unit_desc",fitnessBasic.getBasicUnitDesc());
                                put("amount",fitnessBasic.getBasicAmount());
                                put("group",fitnessBasic.getBasicGroup());
                            }
                        });
                    }
                });
                parents.put(fitnessBasic.getBasicParent(),true);
            } else if (parents.get(fitnessBasic.getBasicParent())) {
                //放子集
               ((List) rel.get("children")).add(new HashMap(){
                    {
                        put("value",fitnessBasic.getBasicType());
                        put("label",fitnessBasic.getBasicTypeDesc());
                        put("unit_desc",fitnessBasic.getBasicUnitDesc());
                        put("amount",fitnessBasic.getBasicAmount());
                        put("group",fitnessBasic.getBasicGroup());
                    }
                });
            }
        }
        tree.add(new HashMap<>(rel));
        return tree;
    }

    /**
     * 导入默认习惯
     *
     * @return
     */
    @Override
    public int importFitnessBasic() {
        return fitnessBasicMapper.importFitnessBasic(new FitnessBasic(){
            {
                setCreateTime(DateUtils.getNowDate());
                setCreateBy(SecurityUtils.getLoginUser().getUsername());
                setBasicId(UUID.randomUUID().toString());
            }
        });
    }
}
